﻿using System.Collections.Generic;
using System.Linq;
using WroxBlog.Models.Interfaces;

namespace WroxBlog.Models.Implementations
{
    public class PostRepository : IPostRepository
    {
        #region IPostRepository Members

        public PostCollection GetRecentPosts(int count)
        {
            WroxBlogDataContext context = new WroxBlogDataContext();

            List<Post> posts = context.Posts.Take(count).OrderByDescending
                            (p => p.DateAdded).ToList();

            return GetPostCollection(posts);
        }

        public PostCollection GetPostsInCategory(string categoryName)
        {
            WroxBlogDataContext context = new WroxBlogDataContext();

            var postsInCategory = from post in context.Posts
                                  where post.Category.Name.ToLower() == categoryName.ToLower()
                                  select post;

            List<Post> posts = postsInCategory.OrderByDescending
                (p => p.DateAdded).ToList();

            return GetPostCollection(posts);
        }

        public Post GetPost(int id)
        {
            WroxBlogDataContext context = new WroxBlogDataContext();

            var selectedPost = (from post in context.Posts
                                where post.ID == id
                                select post).Single();

            return selectedPost;
        }

        #endregion

        #region Private Methods

        private PostCollection GetPostCollection(List<Post> posts)
        {
            PostCollection collection = new PostCollection();
            collection.AddRange(posts);
            return collection;
        }

        #endregion
    }
}
